<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h2>新增和编辑</h2>
    <table>
        <tr>
            <td>标题：</td>
            <td>
                <input type="text" name="title" value="{{blog.title}}">
            </td>
        </tr>
        <tr>
            <td>作者：</td>
            <td>
                <input type="text" name="author" value="{{blog.author}}">
            </td>
        </tr>
        <tr>
            <td>发表时间：</td>
            <td>
                <input type="text" name="publishedTime" value="{{blog.publishedTime}}">
            </td>
        </tr>
        <tr>
            <td>描述：</td>
            <td>
                <input type="text" name="description" value="{{blog.description}}">
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="保存" onclick="btnSave()">
            </td>
            <td>
                <input type="button" value="取消" onclick="btnCancel()">
            </td>
        </tr>
    </table>

    <script src="../js/axios.min.js"></script>
    <script>
        // 保存按钮
        function btnSave() {
            // 获取数据的值
            let arr = document.querySelectorAll('input[name]')
            // console.log(arr);
            let [t1, t2, t3, t4] = arr
            let title = t1.value
            let author = t2.value
            let publishedTime = t3.value
            let description = t4.value
            let obj = { title, author, publishedTime, description }

            // 判断是新增还是修改
            // 获取id值
            let arrString = window.location.href.split('/')
            let id = +arrString[arrString.length - 1]
            // 修改
            if(id >0){
                axios.put('/blogs/' + id , obj).then(res => {
                    if (res.status === 200) {
                        location.href = '/blogs'
                    }
                })
            }else{   // 新增
                // 获取完成后，将数据保存到数据库中
                axios.post('/blogs', obj).then(res => {
                    if (res.status === 200) {
                        location.href = '/blogs'
                    }
                })
            }
        }

        // 取消按钮
        function btnCancel() {
            let isOk = confirm('确定取消吗？')
            if (isOk) {
                location.href = '/blogs'
            }
        }
    </script>
</body>

</html>